<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/7/23
 * Time: 13:37
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Notice extends Base
{
    /**
     * 消息首页展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [
                'n_type' => 1
            ];
            // 推送范围
            if(isset($params['n_range']) && $params['n_range'] != ''){
                $where['n_range'] =$params['n_range'] ;
            }
            // 标题
            if(isset($params['n_title']) && $params['n_title'] != ''){
                $where['n_title'] = ['like', '%' . $params['n_title'] . '%'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('notice')->where($where)->count();// 获取总条数
            $lists = Db::name('notice')
                ->field('n_id, n_title, n_content, n_range, n_send_datetime')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('n_send_datetime desc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 发布消息
     * @return mixed|\think\response\Json
     */
    public function noticeAdd(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            if($params['n_range'] == 2){
                if(trim($params['n_user_id'], ',') == ''){
                    return json(['code' => 100, 'msg' => "can't be empty"]);
                }
            }

            $time = date('Y-m-d H:i:s');
            $data = [
                'n_title' => trim($params['n_title'], ' '), // 标题
                'n_content' => trim($params['n_content'], ' '),// 内容
                'n_type' => 1,// 内容
                'n_range' => $params['n_range'],//推送范围  1 全部  2 个别
                'n_read_user_id' => ',0,', // 已读用户
                'n_del_user_id' => ',0,', // 删除的用户
                'n_send_datetime' => $time, // 推送时间
            ];
            if($params['n_range'] == 1){
                $data['n_user_id'] = 0;
                $ids = Db::table('up_u_user')
                    ->where('user_status',1)
                    ->where('user_id','<>',0)
                    ->column('user_id');
            }else{
                $data['n_user_id'] = ',' . $params['n_user_id'] . ',';
                $ids = explode(',', trim($data['n_user_id'], ','));
            }
            $res = Db::table('up_notice')->insertGetId($data);

            if($res){
                //TODO:推送
                $list = [];//需要推送的用户数组
                foreach($ids as $k => $v){
                    $val = (string)$v;
                    array_push($list, $val);
                }
                try{
                    $this->Jpush(1, $list, $params['n_title'], ['n_id' => $res,'n_type' => 1]);
                }catch(\Exception $e){
                }
                return json(['code' => 200, 'msg' => '发布成功']);
            }else{
                return json(['code' => 100, 'msg' => '发布失败']);
            }
        }
        //所有用户
        $user = Db::table('up_u_user')
            ->field('user_id, user_username,user_phone')
            ->where('user_status', 1)
            ->select();
        
        $this->assign([
            'user' => $user
        ]);
        return $this->fetch('notice/noticeadd');
    }
    
    /**
     * 消息详情
     * @return mixed
     */
    public function noticeDetail(){
        $n_id = input('n_id');
        $info = Db::name('notice')
            ->where('n_id', $n_id)
            ->field('n_title, n_content, n_range, n_send_datetime,n_user_id')
            ->find();
        // 推送范围
        if($info['n_range'] == 1){
            $info['n_range_str'] = '全部';
        }else{
            $info['n_range_str'] = '个别';
            $user = Db::table('up_u_user')
                ->field('user_id, user_username,user_phone')
                ->where('user_id', 'in',$info['n_user_id'])
                ->select();
            $this->assign('user' , $user);
        }
        $this->assign('info' , $info);
        return $this->fetch('notice/noticedetail');
    }
    
    /**
     * 发布的用户列表
     * @return mixed|\think\response\Json
     */
    public function noticeUser(){
        if(request()->isAjax ()){
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $user_ids = Db::table('up_notice')->where('n_id', session('n_id'))->value('n_user_id');
            $where['user_id'] = ['IN', trim($user_ids, ',')];
            $count = Db::name('u_user')->where($where)->count();// 获取总条数
            $lists = Db::name('u_user')
                ->field('user_username, user_image, user_id,user_phone')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('user_time desc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $n_id = input('n_id');
        session('n_id', $n_id);
        return $this->fetch('notice/noticeuser');
    }
    
    /**
     * 删除消息
     * @return \think\response\Json
     */
    public function noticeDel(){
        $n_id = input('id');
        $res = Db::table('up_notice')->delete($n_id);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 批量导出
     * @return \think\response\Json
     */
    public function excelOut(){
        $ids = input('ids');
        if($ids == ''){
            return json(['code' => 100, 'msg' => '请选择需要导出的消息']);
        }
        $where['n_id'] = array('IN',$ids);
        $lists = Db::name('notice')
            ->where($where)
            ->field('n_id, n_title, n_content, n_range, n_send_datetime')
            ->order('n_send_datetime desc')
            ->select();
        
        foreach($lists as $key => $vo){
            //状态
            if($vo['n_range'] == 1) $lists[$key]['n_range'] = '全部';
            if($vo['n_range'] == 2) $lists[$key]['n_range'] = '个别';
        }
        
        $cellname = [
            ['n_id','消息ID',10,'LEFT'],
            ['n_title','推送标题',40,'LEFT'],
            ['n_content','推送内容',80,'LEFT'],
            ['n_range','推送人群',20,'LEFT'],
            ['n_send_datetime','推送时间',20,'LEFT'],
        ];
        $res = exportExcel('系统消息列表','Notice',$cellname,$lists);
        return json($res);
    }
}